//
//  ReportListViewController.m
//  suRead
//
//  Created by lidi on 15/11/11.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "ReportListViewController.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "ServiceNews.h"
#import "UIViewController+HUD.h"
#import "PublishReportViewController.h"
#import "ReportDetailViewController.h"
#import "UIControl+Blocks.h"
#import "M_Report.h"
#import "ReportListCell.h"
#import "UIViewController+EmptyDataSet.h"

@interface ReportListViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *infoTableView;
@property (strong, nonatomic) UISegmentedControl *segment;

@property (strong, nonatomic) NSMutableArray *infoDataArray;

@property (assign, nonatomic) NSInteger currentPageIndex;
@property (strong, nonatomic) NSURLSessionDataTask *requestHandle;
@property (assign, nonatomic) BOOL hasMoreDatas;
@end

@implementation ReportListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weak_self = self;
    
    UIView *navigationBarView = [UIView new];
    navigationBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navigationBarView];
    [navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(navigationBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIView *titleViewContainer = [UIView new];
    [navigationBarView addSubview:titleViewContainer];
    [titleViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(titleViewContainer.superview);
        make.height.equalTo(@44.0f);
    }];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weak_self.navigationController popViewControllerAnimated:YES];
    }];
    [titleViewContainer addSubview:buttonBack];
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonBack.superview);
        make.centerY.equalTo(buttonBack.superview);
        make.width.equalTo(@44.0f);
        make.height.equalTo(@44.0f);
    }];
    
    //爆料
    UIButton *buttonReport = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonReport.titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:16.0f];
    [buttonReport setTitle:@"我要报料" forState:UIControlStateNormal];
    [buttonReport setBackgroundColor:[[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1]];
    buttonReport.layer.cornerRadius = 10.0f;
    buttonReport.layer.masksToBounds = YES;
    [buttonReport addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //保存tags
        [weak_self report];
    }];
    
    [titleViewContainer addSubview:buttonReport];
    [buttonReport mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(buttonReport.superview).offset(-10.0f);
        make.centerY.equalTo(buttonReport.superview);
        make.size.mas_equalTo(CGSizeMake(80.0f, 30.0f));
    }];

    //分段按钮
    self.segment = [UISegmentedControl new];
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.segment insertSegmentWithTitle:@"全部报料" atIndex:0 animated:NO];
    [self.segment insertSegmentWithTitle:@"记者回音" atIndex:1 animated:NO];
    self.segment.layer.masksToBounds = YES;
    self.segment.layer.cornerRadius  = 5;
    self.segment.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.segment.layer.borderWidth = 1.0f;
    self.segment.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:13.0f],
                                             NSForegroundColorAttributeName:[[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1]};
    [self.segment setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:13.0f],
                                               NSForegroundColorAttributeName: [UIColor lightGrayColor]};
    [self.segment setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [self.segment setSelectedSegmentIndex:0];
    [titleViewContainer addSubview:self.segment];
    [self.segment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.segment.superview);
        make.width.mas_equalTo(150.0f);
    }];
    
    //底部横线
    UIView *bottomLine = [UIView new];
    bottomLine.backgroundColor = [UIColor lightGrayColor];
    [titleViewContainer addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomLine.superview);
        make.height.equalTo(@.5f);
    }];
    
    self.infoTableView.tableFooterView = [UIView new];
    [self.infoTableView registerNib:[UINib nibWithNibName:@"ReportListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ReportListCell"];
    
    if(IS_IOS_9) {
        self.infoTableView.contentInset = UIEdgeInsetsMake(20.0f, 0, 0, 0);
    }
    
    self.infoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weak_self refreshDatas];
    }];
    
    
    self.infoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weak_self loadMore];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.infoTableView.mj_header beginRefreshing];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)refreshDatas
{
    [self emptyDataSetClearAllNotice];

    self.currentPageIndex = 1; // 从1开始
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    self.hasMoreDatas = YES;
    
    __weak typeof(self) weak_self = self;
    
    
    if ([self.segment selectedSegmentIndex] == 0) {
        self.requestHandle = [ServiceNews doFetchReportList:self.currentPageIndex pageSize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
            
            [weak_self.infoTableView.mj_header endRefreshing];
            weak_self.infoDataArray = [NSMutableArray array];
            [weak_self.infoDataArray addObjectsFromArray:responseObject];
            [weak_self.infoTableView reloadData];
            
        } failure:^(NSString *message) {
            [weak_self.infoTableView.mj_header endRefreshing];
            [weak_self showHUDText:message];
            
            //重连
            if (!weak_self.infoDataArray || ![weak_self.infoDataArray count]) {
                [weak_self emptyDataSetShowNetWorkAvaliable:^{
                    [weak_self.infoTableView.mj_header beginRefreshing];
                }];
            }
            
        }];
    } else {
        [ServiceNews doFetchNewsManReplyList:self.currentPageIndex
                                    pageSize:DEFAULT_PAGE_SIZE
                                     success:^(id responseObject, NSString *message) {
                                         [weak_self.infoTableView.mj_header endRefreshing];
                                         weak_self.infoDataArray = [NSMutableArray array];
                                         [weak_self.infoDataArray addObjectsFromArray:responseObject];
                                         [weak_self.infoTableView reloadData];

                                     }
                                     failure:^(NSString *message) {
                                         [weak_self.infoTableView.mj_header endRefreshing];
                                         [weak_self showHUDText:message];
                                         //重连
                                         if (!weak_self.infoDataArray || ![weak_self.infoDataArray count]) {
                                             [weak_self emptyDataSetShowNetWorkAvaliable:^{
                                                 [weak_self.infoTableView.mj_header beginRefreshing];
                                             }];
                                         }
                                     }];
    }
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;

    if ([self.segment selectedSegmentIndex] == 0) {
        self.requestHandle = [ServiceNews doFetchReportList:self.currentPageIndex pageSize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
            
            [weak_self.infoTableView.mj_header endRefreshing];
            
            [weak_self.infoDataArray addObjectsFromArray:responseObject];
            [weak_self.infoTableView reloadData];
            
        } failure:^(NSString *message) {
            [weak_self.infoTableView.mj_header endRefreshing];
            [weak_self showHUDText:message];
        }];
    } else {
        [ServiceNews doFetchNewsManReplyList:self.currentPageIndex
                                    pageSize:DEFAULT_PAGE_SIZE
                                     success:^(id responseObject, NSString *message) {
                                         [weak_self.infoTableView.mj_header endRefreshing];
                                         
                                         [weak_self.infoDataArray addObjectsFromArray:responseObject];
                                         [weak_self.infoTableView reloadData];
                                     }
                                     failure:^(NSString *message) {
                                         [weak_self.infoTableView.mj_header endRefreshing];
                                         [weak_self showHUDText:message];
                                     }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.infoDataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReportListCell *cell = (ReportListCell *)[tableView dequeueReusableCellWithIdentifier:@"ReportListCell"];
    M_Report *reportItem = [self.infoDataArray objectAtIndex:indexPath.row];
    cell.reportData = reportItem;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_Report *reportItem = [self.infoDataArray objectAtIndex:indexPath.row];

    UIStoryboard *PersonalStoryboard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
    ReportDetailViewController *controller = [PersonalStoryboard instantiateViewControllerWithIdentifier:@"ReportDetailViewController"];
    controller.hidesBottomBarWhenPushed = YES;
    controller.baoLiaoId = reportItem.f_id;
    [self.navigationController pushViewController:controller animated:YES];

    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)report
{
    UIStoryboard *PersonalStoryboard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
    UIViewController *controller = [PersonalStoryboard instantiateViewControllerWithIdentifier:@"PublishReportViewController"];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)segmentAction:(id)sender
{
    [self.infoTableView.mj_header beginRefreshing];
}

@end
